package org.opu.queryhandler.n.db;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.opu.queryhandler.n.util.Logger;

public class QueryResult {

    public final ResultSet resultSet;
    public final ResultSetMetaData metaData;
    public final SQLWarning warnings;
    private final Statement statement;
    private Logger logger = Logger.getInstance();

    public QueryResult(ResultSet resultSet, SQLWarning warnings,
            Statement statement) throws SQLException {
        this.resultSet = resultSet;
        this.warnings = warnings;
        if (resultSet != null) {
            this.metaData = resultSet.getMetaData();
        } else {
            this.metaData = null;
        }
        this.statement = statement;
    }

    public void clear() {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException ex) {
            logger.fatal(this, ex);
        }
    }

    public Object getObject(int row, int col) {
        try {
            if (resultSet.absolute(row)) {
                return resultSet.getObject(col);
            } else {
                logger.error(this, "Unreacheble row: " + row);
                return "";
            }
        } catch (SQLException ex) {
            logger.error(this, ex);
            return "";
        }
    }

    public int getColumns() {
        try {
            return metaData.getColumnCount();
        } catch (SQLException ex) {
            logger.error(this, ex);
            return 0;
        }
    }

    public int getRows() {
        try {
            resultSet.last();
            return resultSet.getRow();
        } catch (Exception ex) {
            logger.error(this, ex);
            return 0;
        }
    }

    public String[] getHeads() {
        try {
            int count = metaData.getColumnCount();
            List<String> l = new ArrayList<String>(count);
            for (int i = 1; i <= count; i++) {
                l.add(metaData.getColumnName(i));
            }
            return l.toArray(new String[count]);
        } catch (Exception ex) {
            logger.error(this, ex);
            return new String[]{""};
        }
    }

    @Override
    protected void finalize() throws Throwable {
        clear();
    }
}
